package util

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"net"
	"regexp"
	"strings"
)

var (
	UdpConn    *net.UDPConn
	TcpConnMap map[string]*net.TCPConn
	Process    func(conn *net.TCPConn)
)

var ContentLengthRegexp = regexp.MustCompile("Content-Length:(.+)")

func NewRequest(sendValue string, network string, ip string, port int) (err error) {
	switch strings.ToLower(network) {
	case NETWORK_UDP:
		return sendUdpRequest(sendValue, ip, port)
	case NETWORK_TCP:
		return sendTcpRequest(sendValue, ip, port)
	default:
		return errors.New("unknown network error")
	}
}

func sendUdpRequest(sendValue string, ip string, port int) error {
	addr, err := net.ResolveUDPAddr(NETWORK_UDP, fmt.Sprintf("%s:%d", ip, port))
	if err != nil {
		logrus.Panicln("服务udp端口未开放，err:", err)
		return err
	}

	if UdpConn == nil {
		logrus.Infoln("udp连接建立失败", sendValue)
		return errors.New("udp连接建立失败")
	}

	_, err = UdpConn.WriteToUDP([]byte(sendValue), addr)
	if err != nil {
		logrus.Panicln("udp发送错误", sendValue)
		return err
	}
	return nil
}

func sendTcpRequest(sendValue string, ip string, port int) error {
	addr, err := net.ResolveTCPAddr(NETWORK_TCP, fmt.Sprintf("%s:%d", ip, port))
	if err != nil {
		logrus.Panicln("服务tcp端口未开放，err:", err)
		return err
	}

	conn := TcpConnMap[addr.String()]
	if conn == nil {
		conn, err = net.DialTCP(NETWORK_TCP, nil, addr)
		if err != nil {
			return err
		}
		TcpConnMap[addr.String()] = conn
		go Process(conn)
	}

	_, err = conn.Write([]byte(sendValue))
	if err != nil {
		logrus.Infoln("tcp发送错误", sendValue)
		conn.Close()
		delete(TcpConnMap, addr.String())
		return err
	}
	return nil
}
